(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:pager
     * @description
     * # pager 
     */
    angular.module('webApp')
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.retu.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('retu', function() {
            return {
                restrict: "E",
                template: "<div ng-init='initCanvasTu()'><a href='javascript:void(0);'  class='sui-btn btn-link' ng-click='clickinit();'>添加热区</a></div><div id='container3'></div>",
                scope: {
                    ngModel: "=",
                    width: "@",
                    canvasdata: "=",
                    callback: "&",

                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', function($templateCache, $rootScope, $scope, $compile, dataService, $timeout) {
                    //弹窗canvans参数
                    var showDialog = null;
                    var click_text = null;
                    $scope.cid = "";
                    var cpath = "";
                    $scope.isbtn = true;
                    var rect_min_height = 50,
                        rect_min_width = 50;
                    $scope.backgroundImg = null;

                    var stage = null;
                    var layer = null;
                    var yodaImg = null;
                    var yodaGroup = null;
                    $scope.initCanvasTu = function() {
                        $scope.ngModel = $scope.ngModel || {};
                        $timeout(function() {
                            $scope.showCanvasData($scope.ngModel)
                        })
                    }
                    $scope.clickinit = function() {
                        // showDialog = null;
                        // click_text = null;
                        // $scope.cid = "";
                        // cpath = "";
                        // $scope.isbtn = true;
                        rect_min_height = 50;
                        rect_min_width = 50;
                        // $scope.backgroundImg = null;
                        $scope.showPage();

                    }
                    $scope.init = function(cb) {
                        var height = window.innerHeight;
                        console.error("heiht", height);
                        stage = new Konva.Stage({
                            container: 'container2',
                            width: 375,
                            height: height - 20
                        });
                        // console.error("s", stage);
                        // if (!layer) {
                        layer = new Konva.Layer();

                        //创建层容器
                        //创建分组容器
                        yodaGroup = new Konva.Group({
                            x: 0,
                            y: 0,
                            draggable: false
                        });
                        //创建图片容器

                        layer.add(yodaGroup);
                        stage.add(layer);
                        // if (!$scope.backgroundImg) {
                        //添加背景图层拖动点

                        // }
                        cb();
                    }
                    $scope.addhongBao = function(hongBaoObj) {
                        $scope.hongBaoObj = hongBaoObj;
                    }
                    $scope.initCanvas = function() {
                        $timeout(function() {
                            console.error("fffff", $scope.ngModel);
                            if ($scope.ngModel && $scope.ngModel.img) {

                                $scope.addBgImg($scope.ngModel.img.src);
                                // yodaImg.size({
                                //     height: $scope.ngModel.img.height,
                                //     width: $scope.ngModel.img.width
                                // });
                                var circle = yodaGroup.get("Circle");
                                console.error("circle", circle);
                                _.map(circle, function(yuandian) {
                                        yuandian.y(height);
                                    })
                                    // addAnchor(yodaGroup, $scope.ngModel.img.width, $scope.ngModel.img.height, 'bottomRight');
                                    // addAnchor(yodaGroup, 0, $scope.ngModel.img.height, 'bottomLeft');
                                if ($scope.ngModel.alink.length) {
                                    $scope.ngModel.alink.map(function(alink) {
                                        $scope.addJX(alink);
                                    })
                                }
                            }

                        })
                    }
                    $scope.showPage = function() {
                        if (showDialog) {
                            $(".sui-modal").remove();
                        }
                        showDialog = $.alert({
                            backdrop: 'static',
                            keyboard: true,
                            title: '<span>图片热点</span>',
                            body: $templateCache.get("views/directives.retu.html"),
                            okBtn: '{{"ok" | translate}}',
                            closeBtn: true,
                            transition: true,
                            // hasfoot: false,
                            width: '880px',
                            height: 300,
                            show: function(e) {
                                $scope.init(function() {
                                    $scope.initCanvas();
                                });
                                $compile($(e.currentTarget).contents())($scope);
                                return true;
                            },
                            okHide: function(e) {
                                var Layer = stage.get("Layer");
                                var alink = [];
                                if (_.size(Layer)) {
                                    var id = 1;
                                    Layer.map(function(layer) {
                                        var text = layer.get("Text");
                                        if (_.size(text) && text[0].text()) {
                                            var p = text[0].getParent().getParent();
                                            if (p.attrs.x >= 0 && p.attrs.y >= 0) {
                                                var rect = p.get("Rect");
                                                if (_.size(rect)) {
                                                    var button1 = {
                                                        url: text[0].text(),
                                                        height: rect[0].attrs.height,
                                                        width: rect[0].attrs.width,
                                                        x: p.attrs.x,
                                                        y: p.attrs.y,
                                                        type: "rect",
                                                        id: id,
                                                        click_type: "url"
                                                    }
                                                    alink.push(button1);
                                                    id += 1;
                                                } else {
                                                    var circle = p.get("Circle");
                                                    var button2 = {
                                                        url: text[0].text(),
                                                        radius: circle[0].attrs.radius,
                                                        x: p.attrs.x,
                                                        y: p.attrs.y,
                                                        type: "circle",
                                                        id: id,
                                                        click_type: "url"
                                                    }
                                                    alink.push(button2);
                                                    id += 1;
                                                }
                                            }
                                        }
                                    });
                                    if (layer) {
                                        var bgImg = layer.get("Image");
                                        var img = {
                                            src: bgImg[bgImg.length - 1].attrs.image.src,
                                            width: bgImg[bgImg.length - 1].attrs.width,
                                            height: bgImg[bgImg.length - 1].attrs.height
                                        };
                                    }
                                }
                                var retu = {
                                    img: img,
                                    alink: alink
                                }
                                $timeout(function() {
                                    $scope.ngModel = retu
                                })
                                $scope.showCanvasData(retu)
                                $scope.delte();

                                // if ($scope.callback) {
                                //     $scope.callback({ retu: retu });
                                // }
                            },
                        });

                    }
                    $scope.delte = function() {

                        //重置画布数据
                        click_text = null;
                        $scope.cid = "";
                        cpath = "";
                        $scope.isbtn = true;
                        rect_min_height = 50;
                        rect_min_width = 50;
                        $scope.backgroundImg = null;
                        //销毁画布
                        if (stage) {
                            yodaImg.destroy();
                            layer.destroy();
                            stage.clear();
                            stage.destroy();
                        }
                        // $scope.init(function() {});
                    }

                    //设置热点背景图
                    $scope.addBgImg = function(url) {
                        //没有背景图则不创建背景图容器
                        if (!url) {
                            return false;
                        } else {
                            if ($scope.backgroundImg) {
                                stage.destroy();
                                $scope.init(function() {
                                    setImage();
                                })
                            } else {
                                setImage();
                            }

                        }

                        function setImage() {
                            var imageObj2 = new Image();
                            imageObj2.onload = function() {
                                // }
                                var width = 375,
                                    height = (imageObj2.height / imageObj2.width) * 375;
                                if (!yodaImg) {
                                    yodaImg = new Konva.Image({
                                        width: width,
                                        height: height,
                                        draggable: false,
                                        image: imageObj2,
                                    });
                                    addAnchor(yodaGroup, width, height, 'bottomRight');
                                    addAnchor(yodaGroup, 0, height, 'bottomLeft');
                                } else {
                                    yodaImg.image(imageObj2);
                                    yodaImg.height(height);
                                    yodaImg.width(width);
                                    console.error(yodaGroup.get("Circle"));
                                    var circle = yodaGroup.get("Circle");
                                    console.error("circle", circle);
                                    _.map(circle, function(yuandian) {
                                            yuandian.y(height);
                                        })
                                        // addAnchor(yodaGroup, width, height, 'bottomRight');
                                        // addAnchor(yodaGroup, 0, height, 'bottomLeft');
                                }
                                //画布绑定背景图容器 
                                yodaGroup.add(yodaImg);
                                $scope.backgroundImg = url;

                                //渲染背景图容器
                                layer.draw();
                                stage.draw();
                            };
                            imageObj2.src = url;
                        }
                    }

                    //buttonData入参初始化渲染
                    $scope.addJX = function(buttonData) {
                        if (!buttonData && !$scope.requName) {
                            console.debug("热区未设置连接数据");
                            return false;
                        }
                        var rect = new Konva.Rect({
                            width: buttonData ? buttonData.width : 100,
                            height: buttonData ? buttonData.height : 50,
                            fill: 'red',
                            x: 0,
                            y: 0,
                            draggable: false
                        });
                        var text = new Konva.Text({
                            x: 10,
                            y: 5,
                            text: buttonData ? buttonData.url : $scope.requName,
                            fontSize: 15,
                            fontFamily: 'Calibri',
                            fill: 'white',
                            draggable: false,
                            width: buttonData ? (buttonData.width - 15) : (100 - 15),
                            opacity: 0
                        });
                        $scope.requName = "";
                        var g2 = new Konva.Group({
                            x: buttonData ? buttonData.x : 0,
                            y: buttonData ? buttonData.y : 0,
                            draggable: true
                        });
                        g2.on('dragmove', function() {
                            var stage = g2.getStage();
                            var img_bg = stage.get("Image")[0];
                            var rect1 = g2.get('Rect')[0]
                            rect1.attrs.x = 0;
                            if ((img_bg.attrs.width - rect1.attrs.width) < g2.attrs.x) {
                                g2.attrs.x = (img_bg.attrs.width - rect1.attrs.width)
                            } else if (g2.attrs.x < 0) {
                                g2.attrs.x = rect1.attrs.x;
                            }
                            if ((img_bg.attrs.height - rect1.attrs.height) < g2.attrs.y) {
                                g2.attrs.y = (img_bg.attrs.height - rect1.attrs.height)
                            } else if (g2.attrs.y < 0) {
                                g2.attrs.y = 0;
                            }
                            layer.draw();
                        });
                        g2.on("click", function() {
                            var text = this.get("Text")[0];
                            set(text.text());
                            click_text = text;
                        })

                        function set(value) {
                            $scope.$apply(function() {
                                $scope.requName = value;
                            });
                        }
                        var g3 = new Konva.Group({
                            x: 0,
                            y: 0,
                            draggable: false
                        });
                        // if (!layer) {
                        var layer = new Konva.Layer()
                            // }
                            // var layer = new Konva.Layer();
                        g3.add(text);
                        // g3.add(path);
                        g2.add(rect);
                        g2.add(g3);
                        layer.add(g2);
                        stage.add(layer);

                        addAnchor(g2, buttonData ? buttonData.width : 100, 0, 'topRight', 'rect');
                        // addAnchor(g2, 0, 0, 'topLeft', 'rect');
                        addAnchor(g2, buttonData ? buttonData.width : 100, buttonData ? buttonData.height : 50, 'bottomRight', 'rect');
                        // addAnchor(g2, 0, 50, 'bottomLeft', 'rect');
                        layer.draw();
                        // stage.draw();

                    }
                    $scope.setPath = function(path) {
                        console.error("setPath", path);
                        if (path.indexOf("pages") == -1) {
                            console.error("暂时只支持页面事件");
                            return false;
                        }
                        $scope.requName = path;
                        if (click_text) {
                            click_text.text(path);
                            click_text.getLayer().draw();
                            click_text = null;
                        }
                    }

                    function update(groupA, activeAnchor, type) {
                        var group = activeAnchor.getParent();
                        if (group.get('.topLeft')) {
                            var topLeft = group.get('.topLeft')[0];
                        }

                        if (group.get('.topRight')[0]) {
                            var topRight = group.get('.topRight')[0];
                        }
                        var bottomRight = group.get('.bottomRight')[0];
                        if (group.get('.bottomLeft')) {
                            var bottomLeft = group.get('.bottomLeft')[0];
                        }
                        if (!type) {
                            var image = group.get('Image')[0];
                        } else if (type == 'rect') {
                            var rect = group.get('Rect')[0];
                            var text = group.get('Text')[0];
                        }

                        var anchorX = activeAnchor.getX();
                        var anchorY = activeAnchor.getY();
                        // update anchor positions
                        switch (activeAnchor.getName()) {
                            case 'topLeft':
                                if (topRight) {
                                    topRight.y(anchorY);

                                }
                                if (type == 'rect') {
                                    bottomLeft.x(anchorX);
                                }
                                break;
                            case 'topRight':
                                if (topLeft) {
                                    topLeft.y(anchorY);
                                }
                                // bottomRight.x(anchorX);
                                if (type == 'rect') {
                                    bottomRight.x(anchorX);
                                }
                                break;
                            case 'bottomRight':
                                // if(anchorY>topRight.attrs.y&&anchorY<stage.attrs.height){
                                if (bottomLeft) {
                                    bottomLeft.y(anchorY);
                                }
                                // }
                                // topRight.x(anchorX);
                                if (type == 'rect' && topRight) {
                                    topRight.x(anchorX);
                                }
                                break;
                            case 'bottomLeft':
                                if (bottomRight) {
                                    bottomRight.y(anchorY);
                                }
                                // topLeft.x(anchorX);
                                if (type == 'rect') {
                                    topLeft.x(anchorX);
                                }
                                break;
                        }
                        if (topLeft) {
                            if (image) {
                                image.position(topLeft.position());
                            } else {
                                // text.position(rect.position());
                                // text.attrs.x = 10;
                                // text.attrs.y = 15;
                            }
                        }
                        // rect.position(topLeft.position());

                        if (bottomLeft && topLeft && topLeft.attrs.x == bottomLeft.attrs.x && bottomLeft.attrs.x < 0) {
                            groupA.attrs.x = groupA.attrs.x + bottomLeft.attrs.x;
                        }
                        // groupA.position(rect.position());
                        // image.position(topLeft.position());

                        if (topRight) {
                            var width = topRight.getX() - 0;
                        } else {
                            var width = bottomRight.getX() - 0;
                        }
                        if (!topLeft) {
                            var height = bottomRight.getY() - 0;
                        } else {
                            var height = bottomLeft.getY() - topLeft.getY();
                        }
                        if (text && height < (text.attrs.height + text.attrs.y)) {
                            // height = text.attrs.height + text.attrs.y;
                        }
                        console.error("height", height, width);
                        if (height) {
                            // image.width(width);
                            // image.attrs.image.draggable = false
                            if (!type) {
                                image.height(height);
                            } else {
                                if (height > rect_min_height) {
                                    rect.height(height);
                                }
                                if (width > rect_min_width) {
                                    rect.width(width);
                                    text.width(width - 15);
                                }
                            }
                        }
                        var layer = group.getLayer();
                        groupA.draw();
                    }

                    //拖动点的操作
                    function addAnchor(group, x, y, name, type) {
                        var stage = group.getStage();
                        var layer = group.getLayer();
                        var img_bg = stage.get("Image")[0];
                        //拖动点
                        var anchor = new Konva.Circle({
                            x: x,
                            y: y,
                            stroke: '#666',
                            fill: '#ddd',
                            strokeWidth: 2,
                            radius: 8,
                            name: name,
                            draggable: true,
                        });
                        // var topLeft = group.get('.topLeft')[0];
                        // var topRight = group.get('.topRight')[0];
                        // var bottomRight = group.get('.bottomRight')[0];
                        // var bottomLeft = group.get('.bottomLeft')[0];
                        anchor.on('dragmove', function() {
                            if (!type) {
                                anchor.attrs.x = x;
                                if (stage.attrs.height <= anchor.attrs.y) {
                                    anchor.attrs.y = stage.attrs.height;
                                }
                                update(group, this);
                            } else {
                                var rect = group.get("Rect")[0];
                                // var group_Drag=layer.get("Group")[0];
                                if (name == "bottomRight" && anchor.attrs.y <= (rect_min_height)) {
                                    anchor.attrs.y = rect_min_height + 5;
                                    //  +rect.attrs.height
                                } else if (name == "topRight") {
                                    anchor.attrs.y = 0;
                                }
                                if ((name == "bottomRight" || name == "topRight") && anchor.attrs.x <= (rect_min_width)) {
                                    anchor.attrs.x = rect_min_width + 5;
                                }
                                console.error("x", anchor.attrs.x, "rect_width", rect.attrs.width, "group_x", group.attrs.x);
                                console.error("sta", img_bg, anchor, rect, group, (group.attrs.x + anchor.attrs.x));
                                if ((name == "bottomRight" || name == "topRight") && (group.attrs.x + anchor.attrs.x) > img_bg.attrs.width) {
                                    console.error("111111")
                                    anchor.attrs.x = img_bg.attrs.width - group.attrs.x;
                                }
                                // if ((name == "topLeft" || name == "bottomLeft") && ())
                                update(group, this, type);

                            }

                            layer.draw();
                        });
                        anchor.on('mousedown touchstart', function() {

                            group.draggable(false);
                            this.moveToTop();
                        });

                        anchor.on('dragend', function() {
                            if (!type) {
                                group.draggable(false);
                            } else {
                                group.draggable(true);
                            }
                            if (name == "bottomRight" && anchor.attrs.y <= (rect_min_height)) {
                                anchor.attrs.y = rect_min_height + 5;
                                //  +rect.attrs.height
                            }
                            if (name == "bottomRight" && anchor.attrs.x <= (rect_min_width)) {
                                anchor.attrs.x = rect_min_width + 5;
                            }
                            layer.draw();
                        });
                        // add hover styling
                        anchor.on('mouseover', function() {
                            var layer = this.getLayer();
                            document.body.style.cursor = 'pointer';
                            this.strokeWidth(4);
                            layer.draw();
                        });
                        anchor.on('mouseout', function() {
                            var layer = this.getLayer();
                            document.body.style.cursor = 'default';
                            this.strokeWidth(2);
                            layer.draw();
                        });

                        group.add(anchor);
                    }


                    //展示canvas
                    $scope.showCanvasData = function(data) {
                        var content = getCanvaContent(data.img);
                        var imageObj = new Image();
                        var w = data.img.width,
                            h = data.img.height;
                        if ($scope.width) {
                            w = Number($scope.width)
                            h = Number(data.img.height / data.img.width * w);
                        }
                        imageObj.onload = function() {
                            //创建层容器
                            var layer1 = new Konva.Layer();
                            //创建分组容器
                            var yodaGroup1 = new Konva.Group({
                                x: 0,
                                y: 0,
                                draggable: false
                            });
                            //创建图片容器
                            var yodaImg1 = new Konva.Image({
                                width: w,
                                height: h,
                                draggable: false,
                                image: imageObj,
                            });
                            //画布绑定背景图容器 
                            yodaGroup1.add(yodaImg1);
                            layer1.add(yodaGroup1);
                            content.add(layer1);
                            layer1.draw();
                            content.draw();
                            console.error("data", data);
                            data.alink.map(function(a) {
                                var a_w = a.width,
                                    a_h = a.height,
                                    a_x = a.x,
                                    a_y = a.y;
                                if ($scope.width) {
                                    a_w = (w / data.img.width) * a.width;
                                    a_h = (h / data.img.height) * a.height;
                                    a_x = (w / data.img.width) * a.x;
                                    a_y = (h / data.img.height) * a.y
                                }
                                var rect = new Konva.Rect({
                                    width: a_w,
                                    height: a_h,
                                    fill: 'red',
                                    x: 0,
                                    y: 0,
                                    draggable: false
                                });
                                var text = new Konva.Text({
                                    x: 10,
                                    y: 5,
                                    text: a.url,
                                    fontSize: 15,
                                    fontFamily: 'Calibri',
                                    fill: 'white',
                                    draggable: false,
                                    width: (a_w - 15),
                                    opacity: 0
                                });
                                var g2 = new Konva.Group({
                                    x: 0,
                                    y: 0,
                                    draggable: false
                                });
                                g2.add(text);
                                var g3 = new Konva.Group({
                                    x: a_x,
                                    y: a_y,
                                    draggable: false
                                });

                                var layer2 = new Konva.Layer();
                                g3.add(rect);
                                g3.add(g2);
                                layer2.add(g3);
                                content.add(layer2);
                                layer2.draw();
                                // content.draw();
                            })
                        };
                        imageObj.src = data.img.src;
                    }
                    var stage1 = null;

                    function getCanvaContent(img) {
                        var w = img.width,
                            h = img.height;
                        if ($scope.width) {
                            w = Number($scope.width)
                            h = Number(img.height / img.width * w);
                        }
                        if (stage1) {
                            stage1.destroy();
                            return stage1 = new Konva.Stage({
                                container: 'container3',
                                width: w,
                                height: h
                            });
                        } else {
                            return stage1 = new Konva.Stage({
                                container: 'container3',
                                width: w,
                                height: h
                            });
                        }

                    }
                }],
                link: function(scope, element, attrs, ueditor) {}
            }
        });
})();